import {
  Avatar,
  Button,
  Col,
  Dropdown,
  Empty,
  Form,
  Input,
  List,
  MenuProps,
  message,
  Modal,
  Pagination,
  Row,
  Select,
  SelectProps,
  Space,
  Table,
  Tag,
  Tree,
  TreeProps,
} from "antd";
import {
  EllipsisOutlined,
  FieldTimeOutlined,
  ExclamationCircleOutlined,
} from "@ant-design/icons";
import React, { useEffect, useState } from "react";
import "./index.less";
import {
  createDepartment,
  organizationDelete,
  organizationDepartmentList,
  organizationMoveUp,
  organizationToTop,
  organizationTreeList,
  organizationMoveDown,
  organizationToBottom,
  organizationEmployeePage,
  organizationEmployeeDelete,
  organizationEmployeeSave,
} from "@/api/organization";
import { IDepartment } from "@/types/department";
import { IOrganization } from "@/types/organization";
import { IEmployee } from "@/types/employee";
import { ColumnsType } from "antd/es/table";
import { employeeDel, employeeGetEnable } from "@/api/employee";
import dayjs from "dayjs";
import { departmentGetOne } from "@/api/department";
const style: React.CSSProperties = {
  padding: "8px 20px",
  //
};
interface TreeModuleSelect {
  name: string;
  id: string;
  pId: string;
}
const { confirm } = Modal;
const OrganizationPage = () => {
  // 左侧
  useEffect(() => {
    getTreeList();
  }, []);
  // 左侧🌲列表
  const getTreeList = async () => {
    const res = await organizationTreeList();
    function deep(data: IOrganization[]) {
      data.forEach((item) => {
        item.title = (
          <div
            className="flex flex-between"
            onClick={() => handleClickTree(item)}
          >
            <div>{item.name}</div>
            <Dropdown menu={{ items, onClick: (v) => onClick(v, item) }}>
              <EllipsisOutlined />
            </Dropdown>
          </div>
        );
        item.key = item.id;
        if (item.children?.length) {
          deep(item.children);
        }
      });
    }
    deep(res);
    setTreeData(res);
  };
  // 点击树
  const handleClickTree = (item: IOrganization) => {
    setOrganizationInfo(item);
  };
  // 左侧操作处理
  const onClick = ({ key }: { key: string }, info: IOrganization) => {
    switch (key) {
      case "1":
        setTreeModuleSelect({
          ...treeModuleSelect,
          pId: info.pId,
        });
        showModal();
        break;
      case "2":
        setTreeModuleSelect({
          ...treeModuleSelect,
          pId: info.id,
        });
        showModal();
        break;
      case "3":
        handleToTop(info.id);
        break;
      case "4":
        handleMoveUp(info.id);
        break;
      case "5":
        handleMoveDown(info.id);
        break;
      case "6":
        handleTreeDel(info.id);
      case "7":
        handleToBottom(info.id);
        break;

      default:
        break;
    }
  };

  /**
   * 删除
   */
  const handleTreeDel = async (id: string) => {
    const res = await organizationDelete(id);
    if (res) {
      getTreeList();
    }
  };

  /**
   * 上移
   * @param id
   */
  const handleMoveUp = async (id: string) => {
    const res = await organizationMoveUp(id);
    if (res) {
      getTreeList();
    }
  };

  /**
   * 下移
   * @param id
   */
  const handleMoveDown = async (id: string) => {
    const res = await organizationMoveDown(id);
    if (res) {
      getTreeList();
    }
  };

  /**
   * 置顶
   * @param id
   */
  const handleToTop = async (id: string) => {
    const res = await organizationToTop(id);
    if (res) {
      getTreeList();
    }
  };

  /**
   * 置底部
   * @param id
   */
  const handleToBottom = async (id: string) => {
    const res = await organizationToBottom(id);
    if (res) {
      getTreeList();
    }
  };

  const items: MenuProps["items"] = [
    {
      key: "1",
      label: "添加平级部门",
    },
    {
      key: "2",
      label: "添加下级部门",
    },
    {
      key: "3",
      label: "移至首位",
    },
    {
      key: "7",
      label: "移至尾部",
    },
    {
      key: "4",
      label: "向上移动",
    },
    {
      key: "5",
      label: "向下移动",
    },
    {
      key: "6",
      label: "删除",
    },
  ];

  const [treeData, setTreeData] = useState<any[]>([]);

  const IconText = ({ icon, text }: { icon: React.FC; text: string }) => (
    <Space>
      {React.createElement(icon)}
      {text}
    </Space>
  );

  // 删除
  const handleDelRow = (id: string) => {
    confirm({
      icon: <ExclamationCircleOutlined />,
      content: "确定执行此操作么?",
      async onOk() {
        const res = await organizationEmployeeDelete(id);
        if (res) {
          if (pageInfo.page === 1 && pageInfo.pageSize === 10) {
            queryPage();
          } else {
            setPageInfo({ ...pageInfo, page: 1, pageSize: 10 });
          }
        }
      },
      onCancel() {
        message.warning("取消操作");
      },
    });
  };

  // 右侧
  const [pageInfo, setPageInfo] = useState({ page: 1, pageSize: 10, total: 0 });
  const [employeeData, setEmployeeData] = useState<IEmployee[]>([]);
  const [organizationInfo, setOrganizationInfo] = useState<IOrganization>(
    {} as IOrganization
  );
  const [departmentInfo, setDepartmentInfo] = useState<IDepartment>(
    {} as IDepartment
  );
  useEffect(() => {
    queryPage();
  }, [pageInfo.page, pageInfo.pageSize]);

  // 左侧触发渲染右侧
  useEffect(() => {
    if (organizationInfo.id) {
      queryDepartment();
      queryPage();
    }
  }, [organizationInfo.id]);
  // 右侧员工分页
  const queryPage = async () => {
    const res = await organizationEmployeePage({
      ...pageInfo,
      id: organizationInfo.id,
    });
    if (res) {
      setEmployeeData(res.records);
      setPageInfo({
        ...pageInfo,
        total: res.total,
      });
    }
  };
  // 右侧 部门数据
  const queryDepartment = async () => {
    const res = await departmentGetOne(organizationInfo.dId);
    if (res) {
      setDepartmentInfo(res);
    }
  };

  const columns: ColumnsType<IEmployee> = [
    {
      title: "用户名",
      dataIndex: "name",
    },
    {
      title: "账号名",
      dataIndex: "username",
    },
    {
      title: "年龄",
      dataIndex: "birthday",
      render(value, record, index) {
        return dayjs().get("year") - dayjs(value).get("year");
      },
    },
    {
      title: "头像",
      dataIndex: "avatar",
      render(value, record, index) {
        return <Avatar src={value} />;
      },
    },
    {
      title: "性别",
      dataIndex: "gender",
      render(value) {
        return (
          <Tag color={value === 0 ? "blue" : "green"}>
            {value === 0 ? "男" : "女"}
          </Tag>
        );
      },
    },
    {
      title: "手机号",
      dataIndex: "phone",
    },
    {
      title: "操作",
      key: "action",
      render: (_, record) => (
        <Space size="middle">
          <Button type="text" danger onClick={() => handleDelRow(record.id)}>
            删除
          </Button>
        </Space>
      ),
    },
  ];

  const [isTreeModalOpen, setIsTreeModalOpen] = useState(false);
  const [treeModuleSelect, setTreeModuleSelect] = useState<TreeModuleSelect>({
    name: "",
    id: "",
    pId: "0",
  });
  const [treeList, setTreeList] = useState<IDepartment[]>([]);
  useEffect(() => {
    if (isTreeModalOpen) {
      getDepartmentList();
    }
  }, [isTreeModalOpen]);
  const getDepartmentList = async () => {
    const res = await organizationDepartmentList();
    if (res) {
      setTreeList(res);
    }
  };
  const showModal = () => {
    setIsTreeModalOpen(true);
  };

  const handleAddDepartment = async () => {
    await createDepartment({
      name: treeModuleSelect.name,
      dId: treeModuleSelect.id,
      pId: treeModuleSelect.pId,
    });
    getTreeList();
  };

  const handleOk = async () => {
    if (!treeModuleSelect.name) {
      message.warning("请选择部门");
      return;
    }
    await handleAddDepartment();
    onTreeModuleSelectChange("", { label: "", value: "" });
    setIsTreeModalOpen(false);
  };

  const handleCancel = () => {
    onTreeModuleSelectChange("", { label: "", value: "" });
    setIsTreeModalOpen(false);
  };

  const onTreeModuleSelectChange = (
    value: string,
    opt: { value: string; label: string } | { value: string; label: string }[]
  ) => {
    const _opt = opt as { value: string; label: string };
    setTreeModuleSelect({
      ...treeModuleSelect,
      name: _opt.label,
      id: _opt.value,
    });
  };

  const treeModule = () => {
    return (
      <Modal
        title="添加部门"
        open={isTreeModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <Form.Item label="部门名称">
          <Select
            showSearch
            defaultValue={treeModuleSelect.name}
            placeholder="Select a person"
            optionFilterProp="children"
            onChange={(val, opt) => onTreeModuleSelectChange(val, opt)}
            filterOption={(input, option) =>
              (option?.label ?? "").toLowerCase().includes(input.toLowerCase())
            }
            options={treeList.map((w) => ({ label: w.name, value: w.id }))}
          />
        </Form.Item>
      </Modal>
    );
  };
  const treeElement = () => {
    return (
      <div
        style={{
          backgroundColor: "#f5f5f5",
        }}
      >
        {treeData?.length ? (
          <Tree blockNode treeData={treeData} />
        ) : (
          <Button type="primary" block onClick={showModal}>
            添加部门
          </Button>
        )}
      </div>
    );
  };
  const [isEmployeeModalOpen, setEmployeeModalOpen] = useState(false);
  const [employeeModuleSelect, setEmployeeModuleSelect] = useState({
    name: "",
    id: "",
  });
  const [employeeList, setEmployeeList] = useState<IEmployee[]>([]);

  useEffect(() => {
    if (isEmployeeModalOpen) {
      getEmployeeEnableList();
    }
  }, [isEmployeeModalOpen]);
  //
  const getEmployeeEnableList = async () => {
    const res = await employeeGetEnable(1);
    if (res) {
      setEmployeeList(res);
    }
  };
  // 添加员工
  const handleAddEmployee = () => {
    setEmployeeModalOpen(true);
  };
  const handleEmployeeOk = async () => {
    const res = await organizationEmployeeSave({
      eId: employeeModuleSelect.id,
      pId: organizationInfo.id,
    });
    if (res) {
      queryPage();
      setEmployeeModalOpen(false);
    }
  };
  const handleEmployeeCancel = () => {
    setEmployeeModalOpen(false);
  };
  const onEmployeeModuleSelectChange = (
    value: string,
    opt: { value: string; label: string } | { value: string; label: string }[]
  ) => {
    const _opt = opt as { value: string; label: string };
    setEmployeeModuleSelect({
      name: _opt.label,
      id: _opt.value,
    });
  };
  const employeeModule = () => {
    return (
      <Modal
        title="添加员工"
        open={isEmployeeModalOpen}
        onOk={handleEmployeeOk}
        onCancel={handleEmployeeCancel}
      >
        <Form.Item label="员工名称">
          <Select
            showSearch
            defaultValue={employeeModuleSelect.name}
            placeholder="请选择员工"
            optionFilterProp="children"
            onChange={(val, opt) => onEmployeeModuleSelectChange(val, opt)}
            filterOption={(input, option) =>
              (option?.label ?? "").toLowerCase().includes(input.toLowerCase())
            }
            options={employeeList.map((w) => ({ label: w.name, value: w.id }))}
          />
        </Form.Item>
      </Modal>
    );
  };
  const mainElement = () => {
    return (
      <div style={style}>
        {departmentInfo.id ? (
          <>
            <List
              itemLayout="vertical"
              size="large"
              dataSource={[departmentInfo]}
              renderItem={(item) => (
                <List.Item
                  key={item.id}
                  actions={[
                    <IconText
                      icon={FieldTimeOutlined}
                      text={
                        "创建时间：" +
                        new Date(item.createTime).toLocaleString()
                      }
                      key="list-vertical-star-o"
                    />,
                    <IconText
                      icon={FieldTimeOutlined}
                      text={
                        "更新时间：" +
                        new Date(item.updateTime).toLocaleString()
                      }
                    />,
                  ]}
                >
                  <List.Item.Meta
                    avatar={<Avatar src={item.avatar} />}
                    title={<div>{item.name}</div>}
                  />
                </List.Item>
              )}
            />
            <div className="text-right">
              <Button
                className="margin-bottom-16px"
                type="primary"
                onClick={handleAddEmployee}
              >
                添加员工
              </Button>
            </div>
            <Table
              bordered
              dataSource={employeeData}
              columns={columns}
              pagination={{
                total: pageInfo.total,
                showSizeChanger: true,
                showQuickJumper: true,
                onChange: (page, pageSize) => {
                  setPageInfo({
                    ...pageInfo,
                    page,
                    pageSize,
                  });
                },
                showTotal: (total) => `共 ${total} 条数据`,
              }}
            />
          </>
        ) : (
          <Empty description="请选择组织架构" />
        )}
      </div>
    );
  };
  return (
    <>
      <Row gutter={16}>
        <Col className="gutter-row" span={8}>
          {treeElement()}
        </Col>
        <Col className="gutter-row" span={16}>
          {mainElement()}
        </Col>
      </Row>
      {treeModule()}
      {employeeModule()}
    </>
  );
};

export default OrganizationPage;
